package com.example.administrator.bdsjws.services;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v7.app.NotificationCompat;
import android.util.Log;

import com.example.administrator.bdsjws.MyApplication;
import com.example.administrator.bdsjws.R;
import com.example.administrator.bdsjws.utils.MyUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;

import okhttp3.Call;


public class MyDownLoadService extends Service {
    NotificationManager notifi;
    NotificationCompat.Builder notificationBuild;
    public MyDownLoadService() {

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String url=intent.getStringExtra("apkUrl");
        download(url,MyUtil.getPath());
        return super.onStartCommand(intent, flags, startId);
    }

    public void download(String url, File file){
        createvisibile();
        Log.d("aaaaaa","下载");
        OkHttpUtils.get()
                .url(url)
                .build()
                .execute(new FileCallBack(file.getAbsolutePath(),"aaa.apk") {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        notificationBuild.setContentText("下载失败");
                    }

                    @Override
                    public void onResponse(File response, int id) {

                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        notificationBuild.setContentText("正在下载"+(int)(progress*100)+"%");
                        notificationBuild.setProgress(100,(int)(progress*100),false);
                        notifi.notify(0,notificationBuild.build());
                    }
                });
    }

    public void createvisibile(){
        notifi= (NotificationManager) MyApplication.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationBuild= new NotificationCompat.Builder(MyApplication.getContext());
        notificationBuild.setContentTitle("下载中……")
                .setContentText("准备下载……")
                .setSmallIcon(R.mipmap.logo_small)
                .setOngoing(true) //设置他为一个正在进行的通知
                .setAutoCancel(false);
        notifi.notify(0, notificationBuild.build());
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
